<?php

namespace app\api\controller\v40;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAstrData;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRtcRecordComment;
use app\common\cachemodel\zlcr3\Zlcr3ConsultQuestion;
use app\common\cachemodel\zlcr3\Zlcr3Follow;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrTag;
use think\Env;
use think\response\Json;

class ConsultChat extends Auth2
{
    public function getConsultAstrList()
    {
        $type = input('type/d', 0);

        $zlcrAstrModel = new ZlcrAstr();
        $zlcrTagModel = new ZlcrTag();
        $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
        $pageData = $zlcr3ConsultAccountModel->getChatConsultIds(0);
        $testIds = (new AppConfig())->configInfo('rtc')['test_user'];
        $testIds = $testIds ? explode(',', $testIds) : [];
        $pageData = array_diff($pageData, $testIds);
        $consultAstrIds = array_keys($pageData);

        if ($type)
        {
            if ($type === 1)
            {
                $astrIds = $this->user ? (new Zlcr3Follow())->userFollowInfo(1, $this->user['id']) : [];
                $astrIds = $astrIds ?: [];
            } else
            {
                $astrIds = $zlcr3ConsultAccountModel->getChatConsultIds($type);
                $astrIds = array_keys($astrIds);
            }
        } else
        {
            $astrIds = $consultAstrIds;
        }

        $resData = [
            'tags' => [
                [
                    'id' => 1,
                    'name' => '关注',
                ], [
                    'id' => 0,
                    'name' => '全部',
                ]
            ],
        ];

        $tagNameList = $zlcrTagModel->getLevelTag(8, 0);

        foreach ($tagNameList as $tagNameItem)
        {
            $resData['tags'][] = [
                'id' => $tagNameItem['id'],
                'name' => $tagNameItem['tag_name'],
            ];
        }

        $astroList1 = [];
        $astroList2 = [];
        foreach ($consultAstrIds as $astrId)
        {
            if (!in_array((int)$astrId, $astrIds, true))
            {
                continue;
            }
            $astrInfo = $zlcrAstrModel->getInfoById($astrId);
            $consultAstrInfo = $zlcr3ConsultAccountModel->getInfoById($astrId);
            if ($consultAstrInfo['consult_status'] != 1)
            {
                continue;
            }
            $des = $astrInfo['extend']['work_intro'] ?? '';
            $tips = "";
            if ($consultAstrInfo['service_duration'])
            {
                $i = ceil($consultAstrInfo['service_duration'] / 60);
                $tips .= '服务' . ($i > 200 ? '200+' : $i) . '分钟';
            }
            if ($consultAstrInfo['recommended_nums'])
            {
                $tips .= '·' . $consultAstrInfo['recommended_nums'] . "次被推荐";
            }

            $tagIcons = [];
            if ($consultAstrInfo['tids'])
            {
                $tagList = $zlcrTagModel->batchGetInfoByIds($consultAstrInfo['tids']);
                foreach ($tagList as $tagInfo)
                {
                    $tagIcons[] = $tagInfo['templet_url'];
                }
            }
            $tags = [];
            if ($consultAstrInfo['tags'])
            {
                $tagList = $zlcrTagModel->batchGetInfoByIds($consultAstrInfo['tags']);
                foreach ($tagList as $tagInfo)
                {
                    $tags[] = $tagInfo['tag_name'];
                }
            }

            if ($consultAstrInfo['status'] === 1)
            {
                $astroList1[] = [
                    'name' => $astrInfo['nickname'],
                    'avatar' => $astrInfo['avatar'],
                    'tags_icon' => $tagIcons,
                    'tags' => $tags,
                    'des' => $des,
                    'status' => 1,
                    'id' => $astrId,
                    'tips' => $tips,
                ];
            } else
            {
                $astroList2[] = [
                    'name' => $astrInfo['nickname'],
                    'avatar' => $astrInfo['avatar'],
                    'tags_icon' => $tagIcons,
                    'tags' => $tags,
                    'des' => $des,
                    'status' => 2,
                    'id' => $astrId,
                    'tips' => $tips,
                ];
            }
        }
        $resData['astro_list'] = array_merge($astroList1, $astroList2);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 用户当前咨询问题信息
     * @return Json
     * @throws \Exception
     */
    public function getConsultQuestionInfo()
    {
        $zlcr3ConsultQuestionModel = new Zlcr3ConsultQuestion();
        $consultQuestionInfo = $this->user ? $zlcr3ConsultQuestionModel->getUserConsultQuestion($this->user['id']) : [];

        $resData = $zlcr3ConsultQuestionModel->resetConsultQuestion($consultQuestionInfo);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 咨询师排行榜
     */
    public function getConsultAstrRankingList()
    {
        $data = (new Zlcr3ConsultAstrData())->getRankingList(1);

        $i = 60 - date('i');

        $resData = [
            'tip' => "根据咨询师的专业值排名，{$i}分钟后刷新",
            'url' => Env::get('host.domain') . '/web/consult_chat/rankrule.html',
            'data' => (new Zlcr3ConsultAccount())->rankingData($data)
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 咨询师主页
     * @return \think\response\Json
     * @throws \Exception
     */
    public function homePage()
    {
        $astrId = input('astr_id/d', 0);
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        $res = (new ZlcrAstr())->homePage($astrInfo,1,2);
        if ($this->user)
        {
            $followIds = (new Zlcr3Follow())->userFollowInfo(1, $this->user['id']);
            $followIds = $followIds ?: [];
        } else
        {
            $followIds = [];
        }
        $res['follow_status'] = in_array($astrId, $followIds, false) ? 1 : 2;
        return show(config('code.success'), '', $res);
    }

    /**
     * 占星师评价列表
     * @return \think\response\Json
     * @throws \Exception
     */
    public function commentList()
    {
        $astrId = input('astr_id/d', 0);
        $list = (new Zlcr3ConsultChatRtcRecordComment())->astrCommentList($astrId);
        $res = [];
        $tagsModel = new ZlcrTag();
        foreach ($list['data'] as $item)
        {
            $tagInfo = $tagsModel->getInfoById($item['tid'], ['tag_name']);
            $res[] = [
                'name' => $item['name'],
                'avatar' => $item['avatar'],
                'time' => date('Y.m.d H:i', $item['create_time']),
                'tags' => $tagInfo['tag_name'],
                'score' => $item['level'],
                'content' => $item['comment'],
            ];
        }
        $list['data'] = $res;
        return show(config('code.success'), 'Success.', $list);
    }

    /**
     * 获取未读消息数量
     * @return Json
     * @throws \Exception
     */
    public function getNewMsgNum()
    {
        $resData = [
            'reply_num' => 0,
            'rtc_msg_num' => 0,
        ];

        if ($this->user)
        {
            $ids = (new Zlcr2UserQuestion())->getUserUnReadIds($this->user['id']);//未读问题ids
            if ($ids)
            {
                $resData['reply_num'] = 1;
            } else
            {
                $ids = (new Zlcr2QuestionUserView())->getUserUnReadViewIds($this->user['id']);//未读蹭看ids
                if ($ids)
                {
                    $resData['reply_num'] = 1;
                }
            }

            $resData['rtc_msg_num'] = (new Zlcr3ConsultChatRecord())->getUserUnreadAllNum($this->user['id']);
        }

        return show(config('code.success'), '请求成功', $resData);
    }
}
